package com.zhubayi.daka.utils;

import com.zhubayi.daka.pojo.DateTable;
import com.zhubayi.daka.pojo.MyUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.List;

/**
 * @author 祝八一
 */
@Component
public class MailUtil {
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private MailProperties mailProperties;
    @Autowired
    private TemplateEngine templateEngine;
    public void send(MyUser myUser, List<DateTable> tables){
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
        try {
            //发件人
            messageHelper.setFrom(mailProperties.getUsername());
            //收件人
            messageHelper.setTo(myUser.getEmail());
            //主题
            messageHelper.setSubject("打卡消息邮件");
            //发送日期
            messageHelper.setSentDate(new Date());
            //内容
            Context context = new Context();
            context.setVariable("username",myUser.getUsername());
            context.setVariable("status",myUser.getStatus());
            context.setVariable("table",tables );
            //去拿模板
            String mail = templateEngine.process("mail", context);
            //设置内容
            messageHelper.setText(mail,true);
            //发送
            javaMailSender.send(mimeMessage);
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    public void sendUpdate(MyUser myUser){
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
        try {
            //发件人
            messageHelper.setFrom(mailProperties.getUsername());
            //收件人
            messageHelper.setTo(myUser.getEmail());
            //主题
            messageHelper.setSubject("打卡消息邮件");
            //发送日期
            messageHelper.setSentDate(new Date());
            //内容
            Context context = new Context();
            context.setVariable("username",myUser.getUsername());
            //去拿模板
            String mail = templateEngine.process("mail2", context);
            //设置内容
            messageHelper.setText(mail,true);
            //发送
            javaMailSender.send(mimeMessage);
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
